//
//  NetworkRequest.swift
//  Swift_sina
//
//  Created by TFB_WGP on 2017/8/25.
//  Copyright © 2017年 TFB_WGP. All rights reserved.
//

import UIKit
import Alamofire

private let NetworkRequestShareInstance = NetworkRequest()


/// 网络请求方法枚举

class NetworkRequest: NSObject {
    
    class var sharedInstance: NetworkRequest {
        
        return NetworkRequestShareInstance
    }
    //用户账号模型,从写init方法,从沙河加载数据
    lazy var userAccount = WBUserAccount()
    
    /// 是否登录,计算型属性
    var isLogin: Bool {
        return userAccount.access_token != nil
    }
}


extension NetworkRequest{
    //MARK: - Get/Post请求
    func request(method: HTTPMethod = .get, urlString: String, params: [String:Any]?, finished: @escaping(_ response : AnyObject?, _ error : NSError?)->()) {
        
        //使用Alamofire进行网络请求时，调用该方法的参数都是通过getRequest(urlString， params, success :, failture :）传入的，而success传入的其实是一个接受 [String : AnyObject]类型 返回void类型的函数
        Alamofire.request(urlString, method: method, parameters: params).responseJSON { (response) in
            
            if response.result.isSuccess {
                WPPrint(items: "statusCode:\(response.response!.statusCode)")
                if response.response?.statusCode == 403 {
                    WPPrint(items: "token过期")
                    //发送通知,提示用户登录
                    
                    NotificationCenter.default.post(name: NSNotification.Name(WBUserShouldLoginNotifiction), object: "bad token")
                }else {
                    finished(response.result.value as AnyObject,nil)
                }
    
            }
            else{
                finished(nil,response.result.error as NSError?)
            }
        }
    }
    
    //    专门负责token的网络请求
    func tokenRequest(method: HTTPMethod = .get, urlString: String, params: [String:Any]?, finished: @escaping(_ response : AnyObject?, _ error : NSError?)->()) {
        
        //处理token字典
        guard let token = userAccount.access_token else {
            let error = NSError(domain: "token为空", code: -1, userInfo: nil)
            finished(nil,error)
            
            // 发送通知,提示用户登录
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotifiction), object: nil)
            
            return
        }
        var paraDict = params
        if params == nil {
            paraDict = [String:Any]()
        }
        //设置token参数
        paraDict!["access_token"] = token
        request(urlString: urlString, params: paraDict, finished: finished)
    }
}
